Artificial Intelligence Nanodegree

Computer Vision Capstone

Project: Facial Keypoint Detection


Welcome to the final Computer Vision project in the Artificial Intelligence Nanodegree program!

In this project, you’ll combine your knowledge of computer vision techniques and deep learning to build and end-to-end facial keypoint recognition system! Facial keypoints include points around the eyes, nose, and mouth on any face and are used in many applications, from facial tracking to emotion recognition.

There are three main parts to this project:

Part 1 : Investigating OpenCV, pre-processing, and face detection

Part 2 : Training a Convolutional Neural Network (CNN) to detect facial keypoints

Part 3 : Putting parts 1 and 2 together to identify facial keypoints on any image!


*Here's what you need to know to complete the project:

  1. In this notebook, some template code has already been provided for you, and you will need to implement additional functionality to successfully complete this project. You will not need to modify the included code beyond what is requested.

    a. Sections that begin with '(IMPLEMENTATION)' in the header indicate that the following block of code will require additional functionality which you must provide. Instructions will be provided for each section, and the specifics of the implementation are marked in the code block with a 'TODO' statement. Please be sure to read the instructions carefully!

  1. In addition to implementing code, there will be questions that you must answer which relate to the project and your implementation.

    a. Each section where you will answer a question is preceded by a 'Question X' header.

    b. Carefully read each question and provide thorough answers in the following text boxes that begin with 'Answer:'.

Note: Code and Markdown cells can be executed using the Shift + Enter keyboard shortcut. Markdown cells can be edited by double-clicking the cell to enter edit mode.

The rubric contains optional suggestions for enhancing the project beyond the minimum requirements. If you decide to pursue the "(Optional)" sections, you should include the code in this IPython notebook.

Your project submission will be evaluated based on your answers to each of the questions and the code implementations you provide.

Steps to Complete the Project

Each part of the notebook is further broken down into separate steps. Feel free to use the links below to navigate the notebook.

In this project you will get to explore a few of the many computer vision algorithms built into the OpenCV library. This expansive computer vision library is now almost 20 years old and still growing!

The project itself is broken down into three large parts, then even further into separate steps. Make sure to read through each step, and complete any sections that begin with '(IMPLEMENTATION)' in the header; these implementation sections may contain multiple TODOs that will be marked in code. For convenience, we provide links to each of these steps below.

Part 1 : Investigating OpenCV, pre-processing, and face detection

  • Step 0: Detect Faces Using a Haar Cascade Classifier
  • Step 1: Add Eye Detection
  • Step 2: De-noise an Image for Better Face Detection
  • Step 3: Blur an Image and Perform Edge Detection
  • Step 4: Automatically Hide the Identity of an Individual

Part 2 : Training a Convolutional Neural Network (CNN) to detect facial keypoints

  • Step 5: Create a CNN to Recognize Facial Keypoints
  • Step 6: Compile and Train the Model
  • Step 7: Visualize the Loss and Answer Questions

Part 3 : Putting parts 1 and 2 together to identify facial keypoints on any image!

  • Step 8: Build a Robust Facial Keypoints Detector (Complete the CV Pipeline)

Step 0: Detect Faces Using a Haar Cascade Classifier

Have you ever wondered how Facebook automatically tags images with your friends' faces? Or how high-end cameras automatically find and focus on a certain person's face? Applications like these depend heavily on the machine learning task known as face detection - which is the task of automatically finding faces in images containing people.

At its root face detection is a classification problem - that is a problem of distinguishing between distinct classes of things. With face detection these distinct classes are 1) images of human faces and 2) everything else.

We use OpenCV's implementation of Haar feature-based cascade classifiers to detect human faces in images. OpenCV provides many pre-trained face detectors, stored as XML files on github. We have downloaded one of these detectors and stored it in the detector_architectures directory.

Import Resources

In the next python cell, we load in the required libraries for this section of the project.

In [1]:
# Import required libraries for this section

%matplotlib inline

import numpy as np
import matplotlib.pyplot as plt
import math
import cv2                     # OpenCV library for computer vision
from PIL import Image
import time 

Next, we load in and display a test image for performing face detection.

Note: by default OpenCV assumes the ordering of our image's color channels are Blue, then Green, then Red. This is slightly out of order with most image types we'll use in these experiments, whose color channels are ordered Red, then Green, then Blue. In order to switch the Blue and Red channels of our test image around we will use OpenCV's cvtColor function, which you can read more about by checking out some of its documentation located here. This is a general utility function that can do other transformations too like converting a color image to grayscale, and transforming a standard color image to HSV color space.

In [3]:
# Load in color image for face detection
image = cv2.imread('images/test_image_1.jpg')

# Convert the image to RGB colorspace
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

# Plot our image using subplots to specify a size and title
fig = plt.figure(figsize = (8,8))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])

ax1.set_title('Original Image')
ax1.imshow(image)
Out[3]:
<matplotlib.image.AxesImage at 0x240545a5d30>

There are a lot of people - and faces - in this picture. 13 faces to be exact! In the next code cell, we demonstrate how to use a Haar Cascade classifier to detect all the faces in this test image.

This face detector uses information about patterns of intensity in an image to reliably detect faces under varying light conditions. So, to use this face detector, we'll first convert the image from color to grayscale.

Then, we load in the fully trained architecture of the face detector -- found in the file haarcascade_frontalface_default.xml - and use it on our image to find faces!

To learn more about the parameters of the detector see this post.

In [4]:
# Convert the RGB  image to grayscale
gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)

# Extract the pre-trained face detector from an xml file
face_cascade = cv2.CascadeClassifier('detector_architectures/haarcascade_frontalface_default.xml')

# Detect the faces in image
faces = face_cascade.detectMultiScale(gray, 4, 6)

# Print the number of faces detected in the image
print('Number of faces detected:', len(faces))

# Make a copy of the orginal image to draw face detections on
image_with_detections = np.copy(image)

# Get the bounding box for each detected face
for (x,y,w,h) in faces:
    # Add a red bounding box to the detections image
    cv2.rectangle(image_with_detections, (x,y), (x+w,y+h), (255,0,0), 3)
    

# Display the image with the detections
fig = plt.figure(figsize = (8,8))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])

ax1.set_title('Image with Face Detections')
ax1.imshow(image_with_detections)
Number of faces detected: 13
Out[4]:
<matplotlib.image.AxesImage at 0x24054f6c208>

In the above code, faces is a numpy array of detected faces, where each row corresponds to a detected face. Each detected face is a 1D array with four entries that specifies the bounding box of the detected face. The first two entries in the array (extracted in the above code as x and y) specify the horizontal and vertical positions of the top left corner of the bounding box. The last two entries in the array (extracted here as w and h) specify the width and height of the box.


Step 1: Add Eye Detections

There are other pre-trained detectors available that use a Haar Cascade Classifier - including full human body detectors, license plate detectors, and more. A full list of the pre-trained architectures can be found here.

To test your eye detector, we'll first read in a new test image with just a single face.

In [5]:
# Load in color image for face detection
image = cv2.imread('images/james.jpg')

# Convert the image to RGB colorspace
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

# Plot the RGB image
fig = plt.figure(figsize = (6,6))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])

ax1.set_title('Original Image')
ax1.imshow(image)
Out[5]:
<matplotlib.image.AxesImage at 0x24054fc6550>

Notice that even though the image is a black and white image, we have read it in as a color image and so it will still need to be converted to grayscale in order to perform the most accurate face detection.

So, the next steps will be to convert this image to grayscale, then load OpenCV's face detector and run it with parameters that detect this face accurately.

In [6]:
# Convert the RGB  image to grayscale
gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)

# Extract the pre-trained face detector from an xml file
face_cascade = cv2.CascadeClassifier('detector_architectures/haarcascade_frontalface_default.xml')

# Detect the faces in image
faces = face_cascade.detectMultiScale(gray, 1.25, 6)

# Print the number of faces detected in the image
print('Number of faces detected:', len(faces))

# Make a copy of the orginal image to draw face detections on
image_with_detections = np.copy(image)

# Get the bounding box for each detected face
for (x,y,w,h) in faces:
    # Add a red bounding box to the detections image
    cv2.rectangle(image_with_detections, (x,y), (x+w,y+h), (255,0,0), 3)
    

# Display the image with the detections
fig = plt.figure(figsize = (6,6))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])

ax1.set_title('Image with Face Detection')
ax1.imshow(image_with_detections)
Number of faces detected: 1
Out[6]:
<matplotlib.image.AxesImage at 0x240553360b8>

(IMPLEMENTATION) Add an eye detector to the current face detection setup.

A Haar-cascade eye detector can be included in the same way that the face detector was and, in this first task, it will be your job to do just this.

To set up an eye detector, use the stored parameters of the eye cascade detector, called haarcascade_eye.xml, located in the detector_architectures subdirectory. In the next code cell, create your eye detector and store its detections.

A few notes before you get started:

First, make sure to give your loaded eye detector the variable name

eye_cascade

and give the list of eye regions you detect the variable name

eyes

Second, since we've already run the face detector over this image, you should only search for eyes within the rectangular face regions detected in faces. This will minimize false detections.

Lastly, once you've run your eye detector over the facial detection region, you should display the RGB image with both the face detection boxes (in red) and your eye detections (in green) to verify that everything works as expected.

In [7]:
# Make a copy of the original image to plot rectangle detections
image_with_detections = np.copy(image)   

# Loop over the detections and draw their corresponding face detection boxes
for (x,y,w,h) in faces:
    cv2.rectangle(image_with_detections, (x,y), (x+w,y+h),(255,0,0), 3)  
    
# Do not change the code above this comment!

    
## TODO: Add eye detection, using haarcascade_eye.xml, to the current face detector algorithm
eye_cascade = cv2.CascadeClassifier('detector_architectures/haarcascade_eye.xml')

## TODO: Loop over the eye detections and draw their corresponding boxes in green on image_with_detections
for (x,y,w,h) in faces:
    # dont need to draw faces in this one
    roi_gray = gray[y:y+h,x:x+w] # defines region in where there would be eyes
    roi_color = image_with_detections[y:y+h,x:x+w]
    eye = eye_cascade.detectMultiScale(roi_gray)
    for (ex,ey,ew,eh) in eye:
        # goes through each eye and draws a rectangle
        cv2.rectangle(roi_color,(ex,ey),(ex+ew,ey+eh),(0,255,0),2)

# Plot the image with both faces and eyes detected
fig = plt.figure(figsize = (6,6))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])

ax1.set_title('Image with Face and Eye Detection')
ax1.imshow(image_with_detections)
Out[7]:
<matplotlib.image.AxesImage at 0x24055691908>

(Optional) Add face and eye detection to your laptop camera

It's time to kick it up a notch, and add face and eye detection to your laptop's camera! Afterwards, you'll be able to show off your creation like in the gif shown below - made with a completed version of the code!

Notice that not all of the detections here are perfect - and your result need not be perfect either. You should spend a small amount of time tuning the parameters of your detectors to get reasonable results, but don't hold out for perfection. If we wanted perfection we'd need to spend a ton of time tuning the parameters of each detector, cleaning up the input image frames, etc. You can think of this as more of a rapid prototype.

The next cell contains code for a wrapper function called laptop_camera_face_eye_detector that, when called, will activate your laptop's camera. You will place the relevant face and eye detection code in this wrapper function to implement face/eye detection and mark those detections on each image frame that your camera captures.

Before adding anything to the function, you can run it to get an idea of how it works - a small window should pop up showing you the live feed from your camera; you can press any key to close this window.

Note: Mac users may find that activating this function kills the kernel of their notebook every once in a while. If this happens to you, just restart your notebook's kernel, activate cell(s) containing any crucial import statements, and you'll be good to go!

In [8]:
### Add face and eye detection to this laptop camera function 
# Make sure to draw out all faces/eyes found in each frame on the shown video feed

import cv2
import time 

# wrapper function for face/eye detection with your laptop camera
def laptop_camera_go():
    # Create instance of video capturer
    cv2.namedWindow("face detection activated")
    vc = cv2.VideoCapture(0)

    # Try to get the first frame
    if vc.isOpened(): 
        rval, frame = vc.read()
    else:
        rval = False
    
    # Keep the video stream open
    while rval:
        # Plot the image from camera with all the face and eye detections marked
        cv2.imshow("face detection activated", frame)
        
        # Exit functionality - press any key to exit laptop video
        key = cv2.waitKey(20)
        if key > 0: # Exit by pressing any key
            # Destroy windows 
            cv2.destroyAllWindows()
            
            # Make sure window closes on OSx
            for i in range (1,5):
                cv2.waitKey(1)
            return
        
        # Read next frame
        time.sleep(0.07)             # control framerate for computation - default 20 frames per sec
        rval, frame = vc.read()  
        
        #where the face detection starts
        gray = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
        faces = face_cascade.detectMultiScale(gray, 1.1,4)
        
        for (x,y,w,h) in faces:
            cv2.rectangle(frame,(x,y),(x+w,y+h),(255,0,0),2)
            roi_gray = gray[y:y+h, x:x+w]
            roi_color = frame[y:y+h, x:x+w]
            eyes = eye_cascade.detectMultiScale(roi_gray)
            for (ex,ey,ew,eh) in eyes:
                cv2.rectangle(roi_color,(ex,ey),(ex+ew,ey+eh),(0,255,0),2)
In [9]:
# Call the laptop camera face/eye detector function above
laptop_camera_go()

---

Step 2: De-noise an Image for Better Face Detection

Image quality is an important aspect of any computer vision task. Typically, when creating a set of images to train a deep learning network, significant care is taken to ensure that training images are free of visual noise or artifacts that hinder object detection. While computer vision algorithms - like a face detector - are typically trained on 'nice' data such as this, new test data doesn't always look so nice!

When applying a trained computer vision algorithm to a new piece of test data one often cleans it up first before feeding it in. This sort of cleaning - referred to as pre-processing - can include a number of cleaning phases like blurring, de-noising, color transformations, etc., and many of these tasks can be accomplished using OpenCV.

In this short subsection we explore OpenCV's noise-removal functionality to see how we can clean up a noisy image, which we then feed into our trained face detector.

Create a noisy image to work with

In the next cell, we create an artificial noisy version of the previous multi-face image. This is a little exaggerated - we don't typically get images that are this noisy - but image noise, or 'grainy-ness' in a digitial image - is a fairly common phenomenon.

In [11]:
# Load in the multi-face test image again
image = cv2.imread('images/test_image_1.jpg')

# Convert the image copy to RGB colorspace
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

# Make an array copy of this image
image_with_noise = np.asarray(image)

# Create noise - here we add noise sampled randomly from a Gaussian distribution: a common model for noise
noise_level = 40
noise = np.random.randn(image.shape[0],image.shape[1],image.shape[2])*noise_level

# Add this noise to the array image copy
image_with_noise = image_with_noise + noise

# Convert back to uint8 format
image_with_noise = np.asarray([np.uint8(np.clip(i,0,255)) for i in image_with_noise])

# Plot our noisy image!
fig = plt.figure(figsize = (8,8))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])

ax1.set_title('Noisy Image')
ax1.imshow(image_with_noise)
Out[11]:
<matplotlib.image.AxesImage at 0x24055079e80>

In the context of face detection, the problem with an image like this is that - due to noise - we may miss some faces or get false detections.

In the next cell we apply the same trained OpenCV detector with the same settings as before, to see what sort of detections we get.

In [12]:
# Convert the RGB  image to grayscale
gray_noise = cv2.cvtColor(image_with_noise, cv2.COLOR_RGB2GRAY)

# Extract the pre-trained face detector from an xml file
face_cascade = cv2.CascadeClassifier('detector_architectures/haarcascade_frontalface_default.xml')

# Detect the faces in image
faces = face_cascade.detectMultiScale(gray_noise, 4, 6)

# Print the number of faces detected in the image
print('Number of faces detected:', len(faces))

# Make a copy of the orginal image to draw face detections on
image_with_detections = np.copy(image_with_noise)

# Get the bounding box for each detected face
for (x,y,w,h) in faces:
    # Add a red bounding box to the detections image
    cv2.rectangle(image_with_detections, (x,y), (x+w,y+h), (255,0,0), 3)
    

# Display the image with the detections
fig = plt.figure(figsize = (8,8))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])

ax1.set_title('Noisy Image with Face Detections')
ax1.imshow(image_with_detections)
Number of faces detected: 12
Out[12]:
<matplotlib.image.AxesImage at 0x24055093cf8>

With this added noise we now miss one of the faces!

(IMPLEMENTATION) De-noise this image for better face detection

Time to get your hands dirty: using OpenCV's built in color image de-noising functionality called fastNlMeansDenoisingColored - de-noise this image enough so that all the faces in the image are properly detected. Once you have cleaned the image in the next cell, use the cell that follows to run our trained face detector over the cleaned image to check out its detections.

You can find its official documentation here and a useful example here.

Note: you can keep all parameters except photo_render fixed as shown in the second link above. Play around with the value of this parameter - see how it affects the resulting cleaned image.

In [13]:
## TODO: Use OpenCV's built in color image de-noising function to clean up our noisy image!

image_noise_copy = np.copy(image_with_noise)

denoised_img = cv2.fastNlMeansDenoisingColored(image_noise_copy,None,40,40,21,5)

gray_denoised = cv2.cvtColor(denoised_img, cv2.COLOR_RGB2GRAY)
face_cascade=cv2.CascadeClassifier('detector_architectures/haarcascade_frontalface_default.xml')

face = face_cascade.detectMultiScale(gray_denoised,4,6)

print('Number of faces detected: {}'.format(len(face)))
denoised_img_w_detect = np.copy(denoised_img)

for (x,y,w,h) in face:
    cv2.rectangle(denoised_img_w_detect,(x,y),(x+w,y+h),(255,0,0),3)
    
f,(ax1,ax2) = plt.subplots(1,2,figsize = (25,10))

ax1.set_title('Original (the problem)')
ax1.imshow(image_with_detections)

ax2.set_title('denoised')
ax2.imshow(denoised_img_w_detect)
Number of faces detected: 13
Out[13]:
<matplotlib.image.AxesImage at 0x2405512be48>

Step 3: Blur an Image and Perform Edge Detection

Now that we have developed a simple pipeline for detecting faces using OpenCV - let's start playing around with a few fun things we can do with all those detected faces!

Importance of Blur in Edge Detection

Edge detection is a concept that pops up almost everywhere in computer vision applications, as edge-based features (as well as features built on top of edges) are often some of the best features for e.g., object detection and recognition problems.

Edge detection is a dimension reduction technique - by keeping only the edges of an image we get to throw away a lot of non-discriminating information. And typically the most useful kind of edge-detection is one that preserves only the important, global structures (ignoring local structures that aren't very discriminative). So removing local structures / retaining global structures is a crucial pre-processing step to performing edge detection in an image, and blurring can do just that.

Below is an animated gif showing the result of an edge-detected cat taken from Wikipedia, where the image is gradually blurred more and more prior to edge detection. When the animation begins you can't quite make out what it's a picture of, but as the animation evolves and local structures are removed via blurring the cat becomes visible in the edge-detected image.

Edge detection is a convolution performed on the image itself, and you can read about Canny edge detection on this OpenCV documentation page.

Canny edge detection

In the cell below we load in a test image, then apply Canny edge detection on it. The original image is shown on the left panel of the figure, while the edge-detected version of the image is shown on the right. Notice how the result looks very busy - there are too many little details preserved in the image before it is sent to the edge detector. When applied in computer vision applications, edge detection should preserve global structure; doing away with local structures that don't help describe what objects are in the image.

In [14]:
# Load in the image
image = cv2.imread('images/fawzia.jpg')

# Convert to RGB colorspace
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

# Convert to grayscale
gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)  

# Perform Canny edge detection
edges = cv2.Canny(gray,100,200)

# Dilate the image to amplify edges
edges = cv2.dilate(edges, None)

# Plot the RGB and edge-detected image
fig = plt.figure(figsize = (15,15))
ax1 = fig.add_subplot(121)
ax1.set_xticks([])
ax1.set_yticks([])

ax1.set_title('Original Image')
ax1.imshow(image)

ax2 = fig.add_subplot(122)
ax2.set_xticks([])
ax2.set_yticks([])

ax2.set_title('Canny Edges')
ax2.imshow(edges, cmap='gray')
Out[14]:
<matplotlib.image.AxesImage at 0x24055165320>

Without first blurring the image, and removing small, local structures, a lot of irrelevant edge content gets picked up and amplified by the detector (as shown in the right panel above).

(IMPLEMENTATION) Blur the image then perform edge detection

In the next cell, you will repeat this experiment - blurring the image first to remove these local structures, so that only the important boudnary details remain in the edge-detected image.

Blur the image by using OpenCV's filter2d functionality - which is discussed in this documentation page - and use an averaging kernel of width equal to 4.

In [15]:
### TODO: Blur the test imageusing OpenCV's filter2d functionality, 
# Use an averaging kernel, and a kernel width equal to 4
toUse_gray = np.copy(gray)


blured = cv2.GaussianBlur(toUse_gray,(7,7),0)


## TODO: Then perform Canny edge detection and display the output
edges = cv2.Canny(blured,100,200)

edges = cv2.dilate(edges, None)

fig = plt.figure(figsize = (15,15))
ax1 = fig.add_subplot(121)
ax1.set_xticks([])
ax1.set_yticks([])

ax1.set_title('Blured Image')
ax1.imshow(blured,cmap='gray')

ax2 = fig.add_subplot(122)
ax2.set_xticks([])
ax2.set_yticks([])

ax2.set_title('Canny Edges')
ax2.imshow(edges, cmap='gray')
Out[15]:
<matplotlib.image.AxesImage at 0x24055306e48>

Step 4: Automatically Hide the Identity of an Individual

If you film something like a documentary or reality TV, you must get permission from every individual shown on film before you can show their face, otherwise you need to blur it out - by blurring the face a lot (so much so that even the global structures are obscured)! This is also true for projects like Google's StreetView maps - an enormous collection of mapping images taken from a fleet of Google vehicles. Because it would be impossible for Google to get the permission of every single person accidentally captured in one of these images they blur out everyone's faces, the detected images must automatically blur the identity of detected people. Here's a few examples of folks caught in the camera of a Google street view vehicle.

Read in an image to perform identity detection

Let's try this out for ourselves. Use the face detection pipeline built above and what you know about using the filter2D to blur and image, and use these in tandem to hide the identity of the person in the following image - loaded in and printed in the next cell.

In [16]:
# Load in the image
image = cv2.imread('images/gus.jpg')

# Convert the image to RGB colorspace
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

# Display the image
fig = plt.figure(figsize = (6,6))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])
ax1.set_title('Original Image')
ax1.imshow(image)
Out[16]:
<matplotlib.image.AxesImage at 0x240553d1518>

(IMPLEMENTATION) Use blurring to hide the identity of an individual in an image

The idea here is to 1) automatically detect the face in this image, and then 2) blur it out! Make sure to adjust the parameters of the averaging blur filter to completely obscure this person's identity.

In [17]:
## TODO: Implement face detection
gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
    

face_cascade=cv2.CascadeClassifier('detector_architectures/haarcascade_frontalface_default.xml')

faces = face_cascade.detectMultiScale(gray,1.4,6)
print('Number of faces detected: {}'.format(len(faces)))

blur_kernel = np.ones((40,40),np.float32)/1600

image_with_detection = np.copy(image)



## TODO: Blur the bounding box around each detected face using an averaging filter and display the result
for (x,y,w,h) in faces:
    # getting face subsection
    face_section = image[y:y+h,x:x+w]
    blur_face = cv2.filter2D(face_section,-1,blur_kernel) # blures the face
    image_with_detection[y:y+h,x:x+w] = blur_face #assignes that blur to to image
    

# Display the image
fig = plt.figure(figsize = (6,6))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])
ax1.set_title('blured Image')
ax1.imshow(image_with_detection)
Number of faces detected: 1
Out[17]:
<matplotlib.image.AxesImage at 0x2405542f0b8>

(Optional) Build identity protection into your laptop camera

In this optional task you can add identity protection to your laptop camera, using the previously completed code where you added face detection to your laptop camera - and the task above. You should be able to get reasonable results with little parameter tuning - like the one shown in the gif below.

As with the previous video task, to make this perfect would require significant effort - so don't strive for perfection here, strive for reasonable quality.

The next cell contains code a wrapper function called laptop_camera_identity_hider that - when called - will activate your laptop's camera. You need to place the relevant face detection and blurring code developed above in this function in order to blur faces entering your laptop camera's field of view.

Before adding anything to the function you can call it to get a hang of how it works - a small window will pop up showing you the live feed from your camera, you can press any key to close this window.

Note: Mac users may find that activating this function kills the kernel of their notebook every once in a while. If this happens to you, just restart your notebook's kernel, activate cell(s) containing any crucial import statements, and you'll be good to go!

In [18]:
### Insert face detection and blurring code into the wrapper below to create an identity protector on your laptop!
import cv2
import time 

def laptop_camera_go():
    # Create instance of video capturer
    cv2.namedWindow("face detection activated")
    vc = cv2.VideoCapture(0)

    # Try to get the first frame
    if vc.isOpened(): 
        rval, frame = vc.read()
    else:
        rval = False
    
    # Keep video stream open
    while rval:
        # Plot image from camera with detections marked
        cv2.imshow("face detection activated", frame)
        
        # Exit functionality - press any key to exit laptop video
        key = cv2.waitKey(20)
        if key > 0: # Exit by pressing any key
            # Destroy windows
            cv2.destroyAllWindows()
            
            for i in range (1,5):
                cv2.waitKey(1)
            return
        
        # Read next frame
        time.sleep(0.01)             # control framerate for computation - default 20 frames per sec
        rval, frame = vc.read()    
        
        gray = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
        faces = face_cascade.detectMultiScale(gray, 1.1,4)
        
        blur_kernel = np.ones((40,40),np.float32)/1600
        for (x,y,w,h) in faces:
            face_section = frame[y:y+h,x:x+w]
            blur_face = cv2.filter2D(face_section,-1,blur_kernel)
            frame[y:y+h,x:x+w] = blur_face
            
        
        
In [19]:
# Run laptop identity hider
laptop_camera_go()

Step 5: Create a CNN to Recognize Facial Keypoints

OpenCV is often used in practice with other machine learning and deep learning libraries to produce interesting results. In this stage of the project you will create your own end-to-end pipeline - employing convolutional networks in keras along with OpenCV - to apply a "selfie" filter to streaming video and images.

You will start by creating and then training a convolutional network that can detect facial keypoints in a small dataset of cropped images of human faces. We then guide you towards OpenCV to expanding your detection algorithm to more general images. What are facial keypoints? Let's take a look at some examples.

Facial keypoints (also called facial landmarks) are the small blue-green dots shown on each of the faces in the image above - there are 15 keypoints marked in each image. They mark important areas of the face - the eyes, corners of the mouth, the nose, etc. Facial keypoints can be used in a variety of machine learning applications from face and emotion recognition to commercial applications like the image filters popularized by Snapchat.

Below we illustrate a filter that, using the results of this section, automatically places sunglasses on people in images (using the facial keypoints to place the glasses correctly on each face). Here, the facial keypoints have been colored lime green for visualization purposes.

Make a facial keypoint detector

But first things first: how can we make a facial keypoint detector? Well, at a high level, notice that facial keypoint detection is a regression problem. A single face corresponds to a set of 15 facial keypoints (a set of 15 corresponding $(x, y)$ coordinates, i.e., an output point). Because our input data are images, we can employ a convolutional neural network to recognize patterns in our images and learn how to identify these keypoint given sets of labeled data.

In order to train a regressor, we need a training set - a set of facial image / facial keypoint pairs to train on. For this we will be using this dataset from Kaggle. We've already downloaded this data and placed it in the data directory. Make sure that you have both the training and test data files. The training dataset contains several thousand $96 \times 96$ grayscale images of cropped human faces, along with each face's 15 corresponding facial keypoints (also called landmarks) that have been placed by hand, and recorded in $(x, y)$ coordinates. This wonderful resource also has a substantial testing set, which we will use in tinkering with our convolutional network.

To load in this data, run the Python cell below - notice we will load in both the training and testing sets.

The load_data function is in the included utils.py file.

In [35]:
from utils import *

# Load training set
X_train, y_train = load_data()
print("X_train.shape == {}".format(X_train.shape))
print("y_train.shape == {}; y_train.min == {:.3f}; y_train.max == {:.3f}".format(
    y_train.shape, y_train.min(), y_train.max()))

# Load testing set
X_test, _ = load_data(test=True)
print("X_test.shape == {}".format(X_test.shape))
X_train.shape == (2140, 96, 96, 1)
y_train.shape == (2140, 30); y_train.min == -0.920; y_train.max == 0.996
X_test.shape == (1783, 96, 96, 1)

The load_data function in utils.py originates from this excellent blog post, which you are strongly encouraged to read. Please take the time now to review this function. Note how the output values - that is, the coordinates of each set of facial landmarks - have been normalized to take on values in the range $[-1, 1]$, while the pixel values of each input point (a facial image) have been normalized to the range $[0,1]$.

Note: the original Kaggle dataset contains some images with several missing keypoints. For simplicity, the load_data function removes those images with missing labels from the dataset. As an optional extension, you are welcome to amend the load_data function to include the incomplete data points.

Visualize the Training Data

Execute the code cell below to visualize a subset of the training data.

In [36]:
import matplotlib.pyplot as plt
%matplotlib inline

fig = plt.figure(figsize=(20,20))
fig.subplots_adjust(left=0, right=1, bottom=0, top=1, hspace=0.05, wspace=0.05)
for i in range(9):
    ax = fig.add_subplot(3, 3, i + 1, xticks=[], yticks=[])
    plot_data(X_train[i], y_train[i], ax)

For each training image, there are two landmarks per eyebrow (four total), three per eye (six total), four for the mouth, and one for the tip of the nose.

Review the plot_data function in utils.py to understand how the 30-dimensional training labels in y_train are mapped to facial locations, as this function will prove useful for your pipeline.

(IMPLEMENTATION) Specify the CNN Architecture

In this section, you will specify a neural network for predicting the locations of facial keypoints. Use the code cell below to specify the architecture of your neural network. We have imported some layers that you may find useful for this task, but if you need to use more Keras layers, feel free to import them in the cell.

Your network should accept a $96 \times 96$ grayscale image as input, and it should output a vector with 30 entries, corresponding to the predicted (horizontal and vertical) locations of 15 facial keypoints. If you are not sure where to start, you can find some useful starting architectures in this blog, but you are not permitted to copy any of the architectures that you find online.

In [37]:
# Import deep learning resources from Keras
from keras.models import Sequential
from keras.layers import Convolution2D, MaxPooling2D, Dropout
from keras.layers import Flatten, Dense
In [38]:
## TODO: Specify a CNN architecture
# Your model should accept 96x96 pixel graysale images in
# It should have a fully-connected output layer with 30 values (2 for each facial keypoint)

model = Sequential()
model.add(Convolution2D(filters = 16,kernel_size=3,activation='relu',padding='same',input_shape=X_train.shape[1:]))
model.add(MaxPooling2D(pool_size=2))

model.add(Convolution2D(filters = 32,kernel_size=3,activation='relu',padding='same'))
model.add(MaxPooling2D(pool_size=2))



model.add(Convolution2D(filters = 64,kernel_size=3,activation='relu',padding='same'))
model.add(MaxPooling2D(pool_size=2))

model.add(Flatten())

model.add(Dropout(0.6))
model.add(Dense(30))

# Summarize the model
model.summary()
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
conv2d_4 (Conv2D)            (None, 96, 96, 16)        160       
_________________________________________________________________
max_pooling2d_4 (MaxPooling2 (None, 48, 48, 16)        0         
_________________________________________________________________
conv2d_5 (Conv2D)            (None, 48, 48, 32)        4640      
_________________________________________________________________
max_pooling2d_5 (MaxPooling2 (None, 24, 24, 32)        0         
_________________________________________________________________
conv2d_6 (Conv2D)            (None, 24, 24, 64)        18496     
_________________________________________________________________
max_pooling2d_6 (MaxPooling2 (None, 12, 12, 64)        0         
_________________________________________________________________
flatten_2 (Flatten)          (None, 9216)              0         
_________________________________________________________________
dropout_2 (Dropout)          (None, 9216)              0         
_________________________________________________________________
dense_2 (Dense)              (None, 30)                276510    
=================================================================
Total params: 299,806
Trainable params: 299,806
Non-trainable params: 0
_________________________________________________________________

Step 6: Compile and Train the Model

After specifying your architecture, you'll need to compile and train the model to detect facial keypoints'

(IMPLEMENTATION) Compile and Train the Model

Use the compile method to configure the learning process. Experiment with your choice of optimizer; you may have some ideas about which will work best (SGD vs. RMSprop, etc), but take the time to empirically verify your theories.

Use the fit method to train the model. Break off a validation set by setting validation_split=0.2. Save the returned History object in the history variable.

Experiment with your model to minimize the validation loss (measured as mean squared error). A very good model will achieve about 0.0015 loss (though it's possible to do even better). When you have finished training, save your model as an HDF5 file with file path my_model.h5.

In [39]:
from keras.optimizers import SGD, RMSprop, Adagrad, Adadelta, Adam, Adamax, Nadam

## TODO: Compile the model
model.compile(loss='mean_squared_error', optimizer='adamax', metrics=['accuracy'])

## TODO: Train the model
hist = model.fit(X_train,y_train,batch_size=32,epochs=300,validation_split=0.3,verbose=2,shuffle=True )

## TODO: Save the model as model.h5
model.save('my_model.h5')
Train on 1498 samples, validate on 642 samples
Epoch 1/300
 - 12s - loss: 0.0193 - acc: 0.5861 - val_loss: 0.0057 - val_acc: 0.7072
Epoch 2/300
 - 12s - loss: 0.0059 - acc: 0.6609 - val_loss: 0.0041 - val_acc: 0.7087
Epoch 3/300
 - 12s - loss: 0.0050 - acc: 0.6949 - val_loss: 0.0037 - val_acc: 0.7087
Epoch 4/300
 - 12s - loss: 0.0045 - acc: 0.6789 - val_loss: 0.0034 - val_acc: 0.7087
Epoch 5/300
 - 12s - loss: 0.0041 - acc: 0.6883 - val_loss: 0.0030 - val_acc: 0.7134
Epoch 6/300
 - 12s - loss: 0.0037 - acc: 0.6943 - val_loss: 0.0027 - val_acc: 0.7134
Epoch 7/300
 - 12s - loss: 0.0035 - acc: 0.6836 - val_loss: 0.0025 - val_acc: 0.7212
Epoch 8/300
 - 12s - loss: 0.0032 - acc: 0.6896 - val_loss: 0.0023 - val_acc: 0.7181
Epoch 9/300
 - 12s - loss: 0.0030 - acc: 0.7056 - val_loss: 0.0022 - val_acc: 0.7290
Epoch 10/300
 - 12s - loss: 0.0029 - acc: 0.7156 - val_loss: 0.0020 - val_acc: 0.7336
Epoch 11/300
 - 12s - loss: 0.0027 - acc: 0.7143 - val_loss: 0.0020 - val_acc: 0.7336
Epoch 12/300
 - 12s - loss: 0.0026 - acc: 0.7216 - val_loss: 0.0018 - val_acc: 0.7305
Epoch 13/300
 - 12s - loss: 0.0025 - acc: 0.7263 - val_loss: 0.0022 - val_acc: 0.7290
Epoch 14/300
 - 12s - loss: 0.0024 - acc: 0.7256 - val_loss: 0.0018 - val_acc: 0.7290
Epoch 15/300
 - 12s - loss: 0.0024 - acc: 0.7170 - val_loss: 0.0019 - val_acc: 0.7290
Epoch 16/300
 - 12s - loss: 0.0024 - acc: 0.7290 - val_loss: 0.0017 - val_acc: 0.7368
Epoch 17/300
 - 12s - loss: 0.0022 - acc: 0.7223 - val_loss: 0.0017 - val_acc: 0.7477
Epoch 18/300
 - 12s - loss: 0.0022 - acc: 0.7236 - val_loss: 0.0015 - val_acc: 0.7586
Epoch 19/300
 - 12s - loss: 0.0021 - acc: 0.7463 - val_loss: 0.0016 - val_acc: 0.7508
Epoch 20/300
 - 12s - loss: 0.0021 - acc: 0.7450 - val_loss: 0.0016 - val_acc: 0.7461
Epoch 21/300
 - 12s - loss: 0.0020 - acc: 0.7383 - val_loss: 0.0016 - val_acc: 0.7508
Epoch 22/300
 - 12s - loss: 0.0020 - acc: 0.7530 - val_loss: 0.0017 - val_acc: 0.7695
Epoch 23/300
 - 13s - loss: 0.0021 - acc: 0.7336 - val_loss: 0.0017 - val_acc: 0.7445
Epoch 24/300
 - 13s - loss: 0.0019 - acc: 0.7550 - val_loss: 0.0014 - val_acc: 0.7710
Epoch 25/300
 - 13s - loss: 0.0019 - acc: 0.7303 - val_loss: 0.0014 - val_acc: 0.7679
Epoch 26/300
 - 12s - loss: 0.0018 - acc: 0.7550 - val_loss: 0.0014 - val_acc: 0.7617
Epoch 27/300
 - 12s - loss: 0.0019 - acc: 0.7450 - val_loss: 0.0014 - val_acc: 0.7632
Epoch 28/300
 - 12s - loss: 0.0018 - acc: 0.7537 - val_loss: 0.0014 - val_acc: 0.7539
Epoch 29/300
 - 12s - loss: 0.0017 - acc: 0.7603 - val_loss: 0.0014 - val_acc: 0.7601
Epoch 30/300
 - 12s - loss: 0.0017 - acc: 0.7557 - val_loss: 0.0013 - val_acc: 0.7648
Epoch 31/300
 - 12s - loss: 0.0017 - acc: 0.7630 - val_loss: 0.0014 - val_acc: 0.7773
Epoch 32/300
 - 12s - loss: 0.0016 - acc: 0.7737 - val_loss: 0.0014 - val_acc: 0.7601
Epoch 33/300
 - 12s - loss: 0.0016 - acc: 0.7737 - val_loss: 0.0014 - val_acc: 0.7850
Epoch 34/300
 - 12s - loss: 0.0016 - acc: 0.7623 - val_loss: 0.0013 - val_acc: 0.7601
Epoch 35/300
 - 12s - loss: 0.0016 - acc: 0.7704 - val_loss: 0.0017 - val_acc: 0.7679
Epoch 36/300
 - 12s - loss: 0.0015 - acc: 0.7677 - val_loss: 0.0014 - val_acc: 0.7555
Epoch 37/300
 - 12s - loss: 0.0015 - acc: 0.7750 - val_loss: 0.0013 - val_acc: 0.7866
Epoch 38/300
 - 12s - loss: 0.0015 - acc: 0.7797 - val_loss: 0.0013 - val_acc: 0.7726
Epoch 39/300
 - 12s - loss: 0.0016 - acc: 0.7603 - val_loss: 0.0013 - val_acc: 0.7804
Epoch 40/300
 - 12s - loss: 0.0014 - acc: 0.7684 - val_loss: 0.0012 - val_acc: 0.7788
Epoch 41/300
 - 12s - loss: 0.0014 - acc: 0.7623 - val_loss: 0.0013 - val_acc: 0.7944
Epoch 42/300
 - 12s - loss: 0.0014 - acc: 0.7830 - val_loss: 0.0012 - val_acc: 0.7960
Epoch 43/300
 - 12s - loss: 0.0014 - acc: 0.7717 - val_loss: 0.0016 - val_acc: 0.7617
Epoch 44/300
 - 12s - loss: 0.0014 - acc: 0.7710 - val_loss: 0.0017 - val_acc: 0.7850
Epoch 45/300
 - 12s - loss: 0.0016 - acc: 0.7837 - val_loss: 0.0013 - val_acc: 0.7570
Epoch 46/300
 - 12s - loss: 0.0013 - acc: 0.7617 - val_loss: 0.0012 - val_acc: 0.7632
Epoch 47/300
 - 12s - loss: 0.0013 - acc: 0.7911 - val_loss: 0.0012 - val_acc: 0.7897
Epoch 48/300
 - 12s - loss: 0.0013 - acc: 0.7830 - val_loss: 0.0016 - val_acc: 0.7819
Epoch 49/300
 - 12s - loss: 0.0013 - acc: 0.7917 - val_loss: 0.0012 - val_acc: 0.7944
Epoch 50/300
 - 12s - loss: 0.0012 - acc: 0.7797 - val_loss: 0.0012 - val_acc: 0.7695
Epoch 51/300
 - 12s - loss: 0.0012 - acc: 0.8017 - val_loss: 0.0012 - val_acc: 0.7773
Epoch 52/300
 - 12s - loss: 0.0012 - acc: 0.7951 - val_loss: 0.0011 - val_acc: 0.7741
Epoch 53/300
 - 12s - loss: 0.0012 - acc: 0.7997 - val_loss: 0.0011 - val_acc: 0.8037
Epoch 54/300
 - 12s - loss: 0.0013 - acc: 0.7991 - val_loss: 0.0011 - val_acc: 0.8022
Epoch 55/300
 - 12s - loss: 0.0012 - acc: 0.7824 - val_loss: 0.0011 - val_acc: 0.7882
Epoch 56/300
 - 12s - loss: 0.0012 - acc: 0.7937 - val_loss: 0.0011 - val_acc: 0.7897
Epoch 57/300
 - 12s - loss: 0.0012 - acc: 0.7937 - val_loss: 0.0012 - val_acc: 0.8006
Epoch 58/300
 - 12s - loss: 0.0011 - acc: 0.7884 - val_loss: 0.0011 - val_acc: 0.7928
Epoch 59/300
 - 12s - loss: 0.0012 - acc: 0.7997 - val_loss: 0.0011 - val_acc: 0.8037
Epoch 60/300
 - 12s - loss: 0.0011 - acc: 0.8124 - val_loss: 0.0013 - val_acc: 0.8022
Epoch 61/300
 - 12s - loss: 0.0012 - acc: 0.7957 - val_loss: 0.0011 - val_acc: 0.7866
Epoch 62/300
 - 12s - loss: 0.0011 - acc: 0.7911 - val_loss: 0.0011 - val_acc: 0.7960
Epoch 63/300
 - 12s - loss: 0.0011 - acc: 0.7931 - val_loss: 0.0012 - val_acc: 0.7944
Epoch 64/300
 - 12s - loss: 0.0011 - acc: 0.7897 - val_loss: 0.0012 - val_acc: 0.7773
Epoch 65/300
 - 12s - loss: 0.0011 - acc: 0.8037 - val_loss: 0.0010 - val_acc: 0.7928
Epoch 66/300
 - 12s - loss: 0.0010 - acc: 0.8131 - val_loss: 0.0012 - val_acc: 0.7991
Epoch 67/300
 - 12s - loss: 0.0011 - acc: 0.8064 - val_loss: 0.0014 - val_acc: 0.7866
Epoch 68/300
 - 12s - loss: 0.0010 - acc: 0.8004 - val_loss: 0.0011 - val_acc: 0.7835
Epoch 69/300
 - 12s - loss: 0.0010 - acc: 0.8044 - val_loss: 0.0010 - val_acc: 0.8006
Epoch 70/300
 - 12s - loss: 9.8474e-04 - acc: 0.8191 - val_loss: 0.0010 - val_acc: 0.8006
Epoch 71/300
 - 12s - loss: 9.9630e-04 - acc: 0.8224 - val_loss: 0.0012 - val_acc: 0.7975
Epoch 72/300
 - 12s - loss: 9.7414e-04 - acc: 0.8151 - val_loss: 0.0011 - val_acc: 0.7944
Epoch 73/300
 - 12s - loss: 9.5453e-04 - acc: 0.8211 - val_loss: 0.0011 - val_acc: 0.8022
Epoch 74/300
 - 12s - loss: 9.8580e-04 - acc: 0.8238 - val_loss: 0.0010 - val_acc: 0.7882
Epoch 75/300
 - 12s - loss: 9.7190e-04 - acc: 0.8117 - val_loss: 0.0010 - val_acc: 0.8037
Epoch 76/300
 - 12s - loss: 9.2512e-04 - acc: 0.8004 - val_loss: 0.0011 - val_acc: 0.7928
Epoch 77/300
 - 12s - loss: 9.6365e-04 - acc: 0.8211 - val_loss: 0.0011 - val_acc: 0.7944
Epoch 78/300
 - 12s - loss: 8.9860e-04 - acc: 0.8071 - val_loss: 0.0010 - val_acc: 0.7928
Epoch 79/300
 - 12s - loss: 9.0544e-04 - acc: 0.8051 - val_loss: 0.0010 - val_acc: 0.7975
Epoch 80/300
 - 12s - loss: 0.0010 - acc: 0.8144 - val_loss: 0.0010 - val_acc: 0.7960
Epoch 81/300
 - 12s - loss: 9.3034e-04 - acc: 0.8138 - val_loss: 0.0013 - val_acc: 0.8022
Epoch 82/300
 - 12s - loss: 9.2380e-04 - acc: 0.8264 - val_loss: 0.0011 - val_acc: 0.7944
Epoch 83/300
 - 12s - loss: 8.9628e-04 - acc: 0.8191 - val_loss: 9.8426e-04 - val_acc: 0.7975
Epoch 84/300
 - 12s - loss: 8.3876e-04 - acc: 0.8044 - val_loss: 0.0011 - val_acc: 0.8053
Epoch 85/300
 - 12s - loss: 8.5105e-04 - acc: 0.8264 - val_loss: 0.0011 - val_acc: 0.8006
Epoch 86/300
 - 12s - loss: 8.2116e-04 - acc: 0.8218 - val_loss: 0.0010 - val_acc: 0.7960
Epoch 87/300
 - 12s - loss: 8.3170e-04 - acc: 0.8111 - val_loss: 0.0012 - val_acc: 0.8022
Epoch 88/300
 - 12s - loss: 8.1001e-04 - acc: 0.8344 - val_loss: 0.0010 - val_acc: 0.7944
Epoch 89/300
 - 12s - loss: 8.2070e-04 - acc: 0.8324 - val_loss: 0.0011 - val_acc: 0.8037
Epoch 90/300
 - 12s - loss: 7.8917e-04 - acc: 0.8271 - val_loss: 0.0011 - val_acc: 0.8069
Epoch 91/300
 - 12s - loss: 8.5157e-04 - acc: 0.8251 - val_loss: 0.0011 - val_acc: 0.8053
Epoch 92/300
 - 12s - loss: 8.4478e-04 - acc: 0.8311 - val_loss: 9.6953e-04 - val_acc: 0.8053
Epoch 93/300
 - 12s - loss: 7.6926e-04 - acc: 0.8298 - val_loss: 0.0011 - val_acc: 0.8131
Epoch 94/300
 - 12s - loss: 8.0855e-04 - acc: 0.8244 - val_loss: 9.4222e-04 - val_acc: 0.7897
Epoch 95/300
 - 12s - loss: 7.7301e-04 - acc: 0.8111 - val_loss: 0.0011 - val_acc: 0.8069
Epoch 96/300
 - 12s - loss: 8.1066e-04 - acc: 0.8425 - val_loss: 0.0011 - val_acc: 0.8100
Epoch 97/300
 - 12s - loss: 8.1363e-04 - acc: 0.8158 - val_loss: 9.6604e-04 - val_acc: 0.8006
Epoch 98/300
 - 12s - loss: 7.5694e-04 - acc: 0.8391 - val_loss: 9.4895e-04 - val_acc: 0.8006
Epoch 99/300
 - 12s - loss: 7.5511e-04 - acc: 0.8371 - val_loss: 9.2924e-04 - val_acc: 0.7975
Epoch 100/300
 - 12s - loss: 8.0529e-04 - acc: 0.8351 - val_loss: 0.0012 - val_acc: 0.7991
Epoch 101/300
 - 12s - loss: 8.1669e-04 - acc: 0.8278 - val_loss: 0.0010 - val_acc: 0.8069
Epoch 102/300
 - 12s - loss: 7.2124e-04 - acc: 0.8258 - val_loss: 9.8936e-04 - val_acc: 0.7975
Epoch 103/300
 - 12s - loss: 7.5172e-04 - acc: 0.8304 - val_loss: 0.0010 - val_acc: 0.8022
Epoch 104/300
 - 12s - loss: 7.2612e-04 - acc: 0.8378 - val_loss: 9.0923e-04 - val_acc: 0.8006
Epoch 105/300
 - 12s - loss: 7.3647e-04 - acc: 0.8371 - val_loss: 9.3313e-04 - val_acc: 0.8084
Epoch 106/300
 - 12s - loss: 7.5471e-04 - acc: 0.8391 - val_loss: 0.0010 - val_acc: 0.7991
Epoch 107/300
 - 12s - loss: 7.3588e-04 - acc: 0.8324 - val_loss: 9.6706e-04 - val_acc: 0.8022
Epoch 108/300
 - 12s - loss: 7.4439e-04 - acc: 0.8331 - val_loss: 9.2056e-04 - val_acc: 0.8022
Epoch 109/300
 - 12s - loss: 6.9047e-04 - acc: 0.8398 - val_loss: 9.7599e-04 - val_acc: 0.7928
Epoch 110/300
 - 12s - loss: 7.1366e-04 - acc: 0.8518 - val_loss: 0.0011 - val_acc: 0.8069
Epoch 111/300
 - 12s - loss: 8.1246e-04 - acc: 0.8364 - val_loss: 9.1474e-04 - val_acc: 0.8053
Epoch 112/300
 - 12s - loss: 7.2866e-04 - acc: 0.8431 - val_loss: 9.3039e-04 - val_acc: 0.7960
Epoch 113/300
 - 12s - loss: 6.4815e-04 - acc: 0.8485 - val_loss: 9.1684e-04 - val_acc: 0.7975
Epoch 114/300
 - 12s - loss: 6.7347e-04 - acc: 0.8311 - val_loss: 9.0831e-04 - val_acc: 0.8037
Epoch 115/300
 - 12s - loss: 6.6240e-04 - acc: 0.8578 - val_loss: 9.0324e-04 - val_acc: 0.8053
Epoch 116/300
 - 12s - loss: 6.7325e-04 - acc: 0.8405 - val_loss: 9.0743e-04 - val_acc: 0.8084
Epoch 117/300
 - 12s - loss: 6.6535e-04 - acc: 0.8438 - val_loss: 9.2719e-04 - val_acc: 0.8069
Epoch 118/300
 - 12s - loss: 6.5773e-04 - acc: 0.8291 - val_loss: 8.9806e-04 - val_acc: 0.8037
Epoch 119/300
 - 12s - loss: 6.8177e-04 - acc: 0.8458 - val_loss: 9.6330e-04 - val_acc: 0.8178
Epoch 120/300
 - 12s - loss: 6.5595e-04 - acc: 0.8425 - val_loss: 9.6029e-04 - val_acc: 0.8131
Epoch 121/300
 - 12s - loss: 6.3819e-04 - acc: 0.8478 - val_loss: 9.6798e-04 - val_acc: 0.8100
Epoch 122/300
 - 12s - loss: 6.4433e-04 - acc: 0.8451 - val_loss: 8.8792e-04 - val_acc: 0.8131
Epoch 123/300
 - 12s - loss: 6.0613e-04 - acc: 0.8458 - val_loss: 9.0535e-04 - val_acc: 0.8022
Epoch 124/300
 - 12s - loss: 7.0804e-04 - acc: 0.8571 - val_loss: 0.0011 - val_acc: 0.8006
Epoch 125/300
 - 12s - loss: 6.5196e-04 - acc: 0.8411 - val_loss: 9.1005e-04 - val_acc: 0.8053
Epoch 126/300
 - 12s - loss: 6.1372e-04 - acc: 0.8485 - val_loss: 9.0654e-04 - val_acc: 0.8006
Epoch 127/300
 - 12s - loss: 6.2459e-04 - acc: 0.8418 - val_loss: 8.8320e-04 - val_acc: 0.8053
Epoch 128/300
 - 12s - loss: 6.2245e-04 - acc: 0.8405 - val_loss: 9.0141e-04 - val_acc: 0.8100
Epoch 129/300
 - 12s - loss: 6.1476e-04 - acc: 0.8398 - val_loss: 8.7763e-04 - val_acc: 0.8131
Epoch 130/300
 - 12s - loss: 6.2409e-04 - acc: 0.8565 - val_loss: 9.2755e-04 - val_acc: 0.8115
Epoch 131/300
 - 12s - loss: 6.0553e-04 - acc: 0.8551 - val_loss: 9.1351e-04 - val_acc: 0.8115
Epoch 132/300
 - 12s - loss: 5.7561e-04 - acc: 0.8471 - val_loss: 9.1564e-04 - val_acc: 0.8069
Epoch 133/300
 - 12s - loss: 6.3254e-04 - acc: 0.8511 - val_loss: 9.4921e-04 - val_acc: 0.8084
Epoch 134/300
 - 12s - loss: 6.0751e-04 - acc: 0.8445 - val_loss: 0.0010 - val_acc: 0.8053
Epoch 135/300
 - 12s - loss: 5.8261e-04 - acc: 0.8364 - val_loss: 8.9450e-04 - val_acc: 0.8084
Epoch 136/300
 - 12s - loss: 5.8733e-04 - acc: 0.8331 - val_loss: 8.8389e-04 - val_acc: 0.8115
Epoch 137/300
 - 12s - loss: 6.1511e-04 - acc: 0.8571 - val_loss: 9.1599e-04 - val_acc: 0.8053
Epoch 138/300
 - 12s - loss: 5.6195e-04 - acc: 0.8418 - val_loss: 8.8217e-04 - val_acc: 0.8022
Epoch 139/300
 - 12s - loss: 6.3063e-04 - acc: 0.8585 - val_loss: 0.0010 - val_acc: 0.8146
Epoch 140/300
 - 12s - loss: 5.7788e-04 - acc: 0.8485 - val_loss: 8.9040e-04 - val_acc: 0.8053
Epoch 141/300
 - 12s - loss: 5.5960e-04 - acc: 0.8491 - val_loss: 8.7232e-04 - val_acc: 0.8069
Epoch 142/300
 - 12s - loss: 5.7760e-04 - acc: 0.8411 - val_loss: 8.7524e-04 - val_acc: 0.8100
Epoch 143/300
 - 12s - loss: 5.7508e-04 - acc: 0.8565 - val_loss: 8.9435e-04 - val_acc: 0.8115
Epoch 144/300
 - 12s - loss: 5.9428e-04 - acc: 0.8358 - val_loss: 8.9266e-04 - val_acc: 0.8084
Epoch 145/300
 - 12s - loss: 5.6280e-04 - acc: 0.8578 - val_loss: 8.7224e-04 - val_acc: 0.8193
Epoch 146/300
 - 12s - loss: 5.6645e-04 - acc: 0.8578 - val_loss: 9.1381e-04 - val_acc: 0.7944
Epoch 147/300
 - 12s - loss: 5.3535e-04 - acc: 0.8565 - val_loss: 8.6490e-04 - val_acc: 0.8069
Epoch 148/300
 - 12s - loss: 5.1505e-04 - acc: 0.8431 - val_loss: 9.2484e-04 - val_acc: 0.8162
Epoch 149/300
 - 12s - loss: 5.5200e-04 - acc: 0.8538 - val_loss: 8.9179e-04 - val_acc: 0.8131
Epoch 150/300
 - 12s - loss: 5.4338e-04 - acc: 0.8598 - val_loss: 8.5452e-04 - val_acc: 0.8224
Epoch 151/300
 - 12s - loss: 5.6193e-04 - acc: 0.8638 - val_loss: 9.3104e-04 - val_acc: 0.8053
Epoch 152/300
 - 12s - loss: 6.0783e-04 - acc: 0.8458 - val_loss: 9.6870e-04 - val_acc: 0.8146
Epoch 153/300
 - 12s - loss: 5.5603e-04 - acc: 0.8618 - val_loss: 8.7900e-04 - val_acc: 0.8193
Epoch 154/300
 - 12s - loss: 5.1504e-04 - acc: 0.8505 - val_loss: 8.6495e-04 - val_acc: 0.8193
Epoch 155/300
 - 12s - loss: 4.9769e-04 - acc: 0.8598 - val_loss: 8.7964e-04 - val_acc: 0.8178
Epoch 156/300
 - 12s - loss: 5.0777e-04 - acc: 0.8438 - val_loss: 9.2816e-04 - val_acc: 0.8255
Epoch 157/300
 - 12s - loss: 5.3326e-04 - acc: 0.8511 - val_loss: 8.7111e-04 - val_acc: 0.8115
Epoch 158/300
 - 12s - loss: 5.0672e-04 - acc: 0.8658 - val_loss: 8.6818e-04 - val_acc: 0.8224
Epoch 159/300
 - 12s - loss: 4.9354e-04 - acc: 0.8585 - val_loss: 8.6632e-04 - val_acc: 0.8084
Epoch 160/300
 - 12s - loss: 5.4540e-04 - acc: 0.8638 - val_loss: 8.8921e-04 - val_acc: 0.8162
Epoch 161/300
 - 12s - loss: 5.4118e-04 - acc: 0.8578 - val_loss: 8.6349e-04 - val_acc: 0.8240
Epoch 162/300
 - 12s - loss: 4.9596e-04 - acc: 0.8585 - val_loss: 8.8150e-04 - val_acc: 0.8224
Epoch 163/300
 - 12s - loss: 5.1357e-04 - acc: 0.8611 - val_loss: 9.0731e-04 - val_acc: 0.7991
Epoch 164/300
 - 12s - loss: 5.2308e-04 - acc: 0.8645 - val_loss: 8.6961e-04 - val_acc: 0.8146
Epoch 165/300
 - 12s - loss: 5.1171e-04 - acc: 0.8531 - val_loss: 8.9205e-04 - val_acc: 0.8146
Epoch 166/300
 - 12s - loss: 5.1162e-04 - acc: 0.8625 - val_loss: 8.8416e-04 - val_acc: 0.8240
Epoch 167/300
 - 12s - loss: 5.2117e-04 - acc: 0.8558 - val_loss: 8.8387e-04 - val_acc: 0.8162
Epoch 168/300
 - 12s - loss: 4.8321e-04 - acc: 0.8738 - val_loss: 8.5111e-04 - val_acc: 0.8178
Epoch 169/300
 - 12s - loss: 4.7813e-04 - acc: 0.8571 - val_loss: 8.8136e-04 - val_acc: 0.8146
Epoch 170/300
 - 12s - loss: 4.9651e-04 - acc: 0.8525 - val_loss: 8.7715e-04 - val_acc: 0.8022
Epoch 171/300
 - 12s - loss: 4.9345e-04 - acc: 0.8652 - val_loss: 8.5657e-04 - val_acc: 0.8193
Epoch 172/300
 - 12s - loss: 4.7923e-04 - acc: 0.8558 - val_loss: 8.5913e-04 - val_acc: 0.8131
Epoch 173/300
 - 12s - loss: 5.1219e-04 - acc: 0.8531 - val_loss: 9.5864e-04 - val_acc: 0.8084
Epoch 174/300
 - 12s - loss: 5.1032e-04 - acc: 0.8678 - val_loss: 8.6806e-04 - val_acc: 0.8146
Epoch 175/300
 - 12s - loss: 4.7376e-04 - acc: 0.8605 - val_loss: 8.8504e-04 - val_acc: 0.8100
Epoch 176/300
 - 12s - loss: 4.6738e-04 - acc: 0.8652 - val_loss: 8.7819e-04 - val_acc: 0.8193
Epoch 177/300
 - 12s - loss: 4.8469e-04 - acc: 0.8685 - val_loss: 8.5602e-04 - val_acc: 0.8178
Epoch 178/300
 - 12s - loss: 4.7865e-04 - acc: 0.8638 - val_loss: 0.0010 - val_acc: 0.8069
Epoch 179/300
 - 12s - loss: 4.9366e-04 - acc: 0.8525 - val_loss: 8.4763e-04 - val_acc: 0.8162
Epoch 180/300
 - 12s - loss: 4.8547e-04 - acc: 0.8718 - val_loss: 8.6548e-04 - val_acc: 0.8146
Epoch 181/300
 - 12s - loss: 4.6653e-04 - acc: 0.8551 - val_loss: 8.9512e-04 - val_acc: 0.8333
Epoch 182/300
 - 12s - loss: 4.9569e-04 - acc: 0.8611 - val_loss: 8.4959e-04 - val_acc: 0.8255
Epoch 183/300
 - 12s - loss: 4.7099e-04 - acc: 0.8458 - val_loss: 8.9609e-04 - val_acc: 0.8240
Epoch 184/300
 - 12s - loss: 4.6934e-04 - acc: 0.8611 - val_loss: 8.7221e-04 - val_acc: 0.8193
Epoch 185/300
 - 12s - loss: 4.5349e-04 - acc: 0.8531 - val_loss: 8.6119e-04 - val_acc: 0.8255
Epoch 186/300
 - 12s - loss: 4.6341e-04 - acc: 0.8665 - val_loss: 8.9086e-04 - val_acc: 0.8131
Epoch 187/300
 - 12s - loss: 4.6334e-04 - acc: 0.8678 - val_loss: 8.3860e-04 - val_acc: 0.8084
Epoch 188/300
 - 12s - loss: 4.6178e-04 - acc: 0.8805 - val_loss: 8.4263e-04 - val_acc: 0.8084
Epoch 189/300
 - 12s - loss: 4.6606e-04 - acc: 0.8665 - val_loss: 8.8778e-04 - val_acc: 0.8053
Epoch 190/300
 - 12s - loss: 4.2757e-04 - acc: 0.8591 - val_loss: 8.4232e-04 - val_acc: 0.8193
Epoch 191/300
 - 12s - loss: 4.2935e-04 - acc: 0.8685 - val_loss: 8.4194e-04 - val_acc: 0.8224
Epoch 192/300
 - 12s - loss: 4.5229e-04 - acc: 0.8571 - val_loss: 9.6393e-04 - val_acc: 0.8178
Epoch 193/300
 - 12s - loss: 4.7929e-04 - acc: 0.8545 - val_loss: 8.6420e-04 - val_acc: 0.8224
Epoch 194/300
 - 12s - loss: 4.4272e-04 - acc: 0.8738 - val_loss: 8.7925e-04 - val_acc: 0.8100
Epoch 195/300
 - 12s - loss: 4.3623e-04 - acc: 0.8611 - val_loss: 8.3671e-04 - val_acc: 0.8209
Epoch 196/300
 - 12s - loss: 4.5116e-04 - acc: 0.8638 - val_loss: 9.5304e-04 - val_acc: 0.8131
Epoch 197/300
 - 12s - loss: 4.5644e-04 - acc: 0.8772 - val_loss: 8.4619e-04 - val_acc: 0.8146
Epoch 198/300
 - 12s - loss: 4.4070e-04 - acc: 0.8658 - val_loss: 8.4020e-04 - val_acc: 0.8053
Epoch 199/300
 - 12s - loss: 4.6003e-04 - acc: 0.8692 - val_loss: 8.8871e-04 - val_acc: 0.8146
Epoch 200/300
 - 12s - loss: 4.8482e-04 - acc: 0.8652 - val_loss: 8.5220e-04 - val_acc: 0.8146
Epoch 201/300
 - 12s - loss: 4.3083e-04 - acc: 0.8652 - val_loss: 8.3770e-04 - val_acc: 0.8115
Epoch 202/300
 - 12s - loss: 4.2961e-04 - acc: 0.8685 - val_loss: 9.1127e-04 - val_acc: 0.8193
Epoch 203/300
 - 12s - loss: 4.4960e-04 - acc: 0.8625 - val_loss: 8.3214e-04 - val_acc: 0.8146
Epoch 204/300
 - 12s - loss: 4.2120e-04 - acc: 0.8745 - val_loss: 8.5062e-04 - val_acc: 0.8115
Epoch 205/300
 - 12s - loss: 4.2390e-04 - acc: 0.8665 - val_loss: 8.5020e-04 - val_acc: 0.8349
Epoch 206/300
 - 12s - loss: 4.2537e-04 - acc: 0.8725 - val_loss: 8.4804e-04 - val_acc: 0.8240
Epoch 207/300
 - 12s - loss: 4.1708e-04 - acc: 0.8665 - val_loss: 8.8945e-04 - val_acc: 0.8178
Epoch 208/300
 - 12s - loss: 4.2715e-04 - acc: 0.8698 - val_loss: 8.9658e-04 - val_acc: 0.8084
Epoch 209/300
 - 12s - loss: 4.4611e-04 - acc: 0.8571 - val_loss: 8.7510e-04 - val_acc: 0.8178
Epoch 210/300
 - 12s - loss: 4.2540e-04 - acc: 0.8611 - val_loss: 8.9810e-04 - val_acc: 0.8084
Epoch 211/300
 - 12s - loss: 4.2981e-04 - acc: 0.8778 - val_loss: 8.4278e-04 - val_acc: 0.8131
Epoch 212/300
 - 12s - loss: 4.3890e-04 - acc: 0.8785 - val_loss: 9.2815e-04 - val_acc: 0.8209
Epoch 213/300
 - 12s - loss: 4.1740e-04 - acc: 0.8672 - val_loss: 8.7704e-04 - val_acc: 0.8100
Epoch 214/300
 - 12s - loss: 4.0792e-04 - acc: 0.8725 - val_loss: 8.8017e-04 - val_acc: 0.8146
Epoch 215/300
 - 12s - loss: 4.3156e-04 - acc: 0.8705 - val_loss: 8.4849e-04 - val_acc: 0.8115
Epoch 216/300
 - 12s - loss: 4.1825e-04 - acc: 0.8685 - val_loss: 8.4520e-04 - val_acc: 0.8178
Epoch 217/300
 - 12s - loss: 4.1917e-04 - acc: 0.8678 - val_loss: 8.5080e-04 - val_acc: 0.8131
Epoch 218/300
 - 12s - loss: 4.1705e-04 - acc: 0.8712 - val_loss: 8.3838e-04 - val_acc: 0.8271
Epoch 219/300
 - 12s - loss: 4.1051e-04 - acc: 0.8578 - val_loss: 8.7543e-04 - val_acc: 0.8115
Epoch 220/300
 - 12s - loss: 4.2124e-04 - acc: 0.8678 - val_loss: 8.3634e-04 - val_acc: 0.8209
Epoch 221/300
 - 12s - loss: 4.0858e-04 - acc: 0.8685 - val_loss: 8.6344e-04 - val_acc: 0.8115
Epoch 222/300
 - 12s - loss: 4.0934e-04 - acc: 0.8625 - val_loss: 8.2825e-04 - val_acc: 0.8193
Epoch 223/300
 - 12s - loss: 4.1277e-04 - acc: 0.8778 - val_loss: 8.7686e-04 - val_acc: 0.8162
Epoch 224/300
 - 12s - loss: 3.9350e-04 - acc: 0.8765 - val_loss: 8.4936e-04 - val_acc: 0.8193
Epoch 225/300
 - 12s - loss: 4.0087e-04 - acc: 0.8658 - val_loss: 8.3624e-04 - val_acc: 0.8255
Epoch 226/300
 - 12s - loss: 4.3036e-04 - acc: 0.8565 - val_loss: 8.3814e-04 - val_acc: 0.8069
Epoch 227/300
 - 12s - loss: 3.8645e-04 - acc: 0.8625 - val_loss: 8.4071e-04 - val_acc: 0.8162
Epoch 228/300
 - 12s - loss: 3.8970e-04 - acc: 0.8792 - val_loss: 8.2615e-04 - val_acc: 0.8162
Epoch 229/300
 - 12s - loss: 3.9784e-04 - acc: 0.8665 - val_loss: 8.5911e-04 - val_acc: 0.8209
Epoch 230/300
 - 12s - loss: 3.9140e-04 - acc: 0.8758 - val_loss: 8.5524e-04 - val_acc: 0.8209
Epoch 231/300
 - 12s - loss: 4.0836e-04 - acc: 0.8825 - val_loss: 8.7780e-04 - val_acc: 0.8224
Epoch 232/300
 - 12s - loss: 4.0911e-04 - acc: 0.8645 - val_loss: 8.3592e-04 - val_acc: 0.8224
Epoch 233/300
 - 12s - loss: 3.9817e-04 - acc: 0.8658 - val_loss: 8.2128e-04 - val_acc: 0.8053
Epoch 234/300
 - 12s - loss: 4.0365e-04 - acc: 0.8765 - val_loss: 8.2654e-04 - val_acc: 0.8069
Epoch 235/300
 - 12s - loss: 4.1431e-04 - acc: 0.8672 - val_loss: 8.5877e-04 - val_acc: 0.8084
Epoch 236/300
 - 12s - loss: 3.9911e-04 - acc: 0.8792 - val_loss: 8.6149e-04 - val_acc: 0.8100
Epoch 237/300
 - 12s - loss: 3.8780e-04 - acc: 0.8778 - val_loss: 8.3424e-04 - val_acc: 0.8115
Epoch 238/300
 - 12s - loss: 4.0879e-04 - acc: 0.8692 - val_loss: 8.3719e-04 - val_acc: 0.8084
Epoch 239/300
 - 12s - loss: 4.0668e-04 - acc: 0.8652 - val_loss: 8.4706e-04 - val_acc: 0.8069
Epoch 240/300
 - 12s - loss: 3.8051e-04 - acc: 0.8825 - val_loss: 8.6137e-04 - val_acc: 0.8209
Epoch 241/300
 - 12s - loss: 3.8779e-04 - acc: 0.8712 - val_loss: 8.3019e-04 - val_acc: 0.8302
Epoch 242/300
 - 12s - loss: 3.9786e-04 - acc: 0.8685 - val_loss: 8.2807e-04 - val_acc: 0.8255
Epoch 243/300
 - 12s - loss: 3.8678e-04 - acc: 0.8758 - val_loss: 8.5506e-04 - val_acc: 0.8037
Epoch 244/300
 - 12s - loss: 3.8748e-04 - acc: 0.8745 - val_loss: 8.6034e-04 - val_acc: 0.8255
Epoch 245/300
 - 12s - loss: 3.9954e-04 - acc: 0.8638 - val_loss: 8.3843e-04 - val_acc: 0.8162
Epoch 246/300
 - 12s - loss: 4.0441e-04 - acc: 0.8718 - val_loss: 8.5141e-04 - val_acc: 0.8240
Epoch 247/300
 - 12s - loss: 3.8554e-04 - acc: 0.8792 - val_loss: 8.4487e-04 - val_acc: 0.8193
Epoch 248/300
 - 12s - loss: 3.8058e-04 - acc: 0.8665 - val_loss: 8.4314e-04 - val_acc: 0.8255
Epoch 249/300
 - 12s - loss: 3.8616e-04 - acc: 0.8618 - val_loss: 9.5228e-04 - val_acc: 0.8131
Epoch 250/300
 - 12s - loss: 3.8362e-04 - acc: 0.8658 - val_loss: 8.2451e-04 - val_acc: 0.8084
Epoch 251/300
 - 12s - loss: 3.7500e-04 - acc: 0.8725 - val_loss: 8.4461e-04 - val_acc: 0.8209
Epoch 252/300
 - 12s - loss: 3.7705e-04 - acc: 0.8765 - val_loss: 8.3469e-04 - val_acc: 0.8115
Epoch 253/300
 - 12s - loss: 3.7967e-04 - acc: 0.8618 - val_loss: 9.0037e-04 - val_acc: 0.8053
Epoch 254/300
 - 12s - loss: 3.6226e-04 - acc: 0.8792 - val_loss: 8.6910e-04 - val_acc: 0.8100
Epoch 255/300
 - 12s - loss: 3.7459e-04 - acc: 0.8825 - val_loss: 8.3233e-04 - val_acc: 0.8209
Epoch 256/300
 - 12s - loss: 3.8384e-04 - acc: 0.8778 - val_loss: 8.7209e-04 - val_acc: 0.8115
Epoch 257/300
 - 12s - loss: 3.8363e-04 - acc: 0.8718 - val_loss: 8.6663e-04 - val_acc: 0.8178
Epoch 258/300
 - 12s - loss: 3.6956e-04 - acc: 0.8772 - val_loss: 8.3876e-04 - val_acc: 0.8146
Epoch 259/300
 - 12s - loss: 3.9131e-04 - acc: 0.8658 - val_loss: 8.2422e-04 - val_acc: 0.8069
Epoch 260/300
 - 12s - loss: 3.6419e-04 - acc: 0.8725 - val_loss: 8.3285e-04 - val_acc: 0.8193
Epoch 261/300
 - 12s - loss: 3.5982e-04 - acc: 0.8812 - val_loss: 8.4274e-04 - val_acc: 0.8193
Epoch 262/300
 - 12s - loss: 3.6698e-04 - acc: 0.8778 - val_loss: 8.3117e-04 - val_acc: 0.7975
Epoch 263/300
 - 12s - loss: 3.7028e-04 - acc: 0.8745 - val_loss: 9.1651e-04 - val_acc: 0.8209
Epoch 264/300
 - 12s - loss: 3.6794e-04 - acc: 0.8818 - val_loss: 8.4688e-04 - val_acc: 0.8178
Epoch 265/300
 - 12s - loss: 3.7191e-04 - acc: 0.8785 - val_loss: 9.2955e-04 - val_acc: 0.8380
Epoch 266/300
 - 12s - loss: 3.6065e-04 - acc: 0.8752 - val_loss: 8.2931e-04 - val_acc: 0.8115
Epoch 267/300
 - 13s - loss: 3.6140e-04 - acc: 0.8778 - val_loss: 8.3945e-04 - val_acc: 0.8131
Epoch 268/300
 - 12s - loss: 3.6396e-04 - acc: 0.8718 - val_loss: 8.1523e-04 - val_acc: 0.8162
Epoch 269/300
 - 12s - loss: 3.4772e-04 - acc: 0.8732 - val_loss: 8.3541e-04 - val_acc: 0.8100
Epoch 270/300
 - 12s - loss: 3.6631e-04 - acc: 0.8638 - val_loss: 8.3540e-04 - val_acc: 0.8178
Epoch 271/300
 - 12s - loss: 3.6383e-04 - acc: 0.8858 - val_loss: 8.1676e-04 - val_acc: 0.8146
Epoch 272/300
 - 12s - loss: 3.5154e-04 - acc: 0.8792 - val_loss: 8.5048e-04 - val_acc: 0.8209
Epoch 273/300
 - 12s - loss: 3.6214e-04 - acc: 0.8672 - val_loss: 8.7031e-04 - val_acc: 0.8146
Epoch 274/300
 - 12s - loss: 3.6368e-04 - acc: 0.8772 - val_loss: 8.3236e-04 - val_acc: 0.8193
Epoch 275/300
 - 12s - loss: 3.6905e-04 - acc: 0.8732 - val_loss: 8.3202e-04 - val_acc: 0.8069
Epoch 276/300
 - 12s - loss: 3.5841e-04 - acc: 0.8785 - val_loss: 8.2672e-04 - val_acc: 0.8178
Epoch 277/300
 - 12s - loss: 3.5476e-04 - acc: 0.8625 - val_loss: 8.3327e-04 - val_acc: 0.8146
Epoch 278/300
 - 12s - loss: 3.5627e-04 - acc: 0.8765 - val_loss: 8.1804e-04 - val_acc: 0.8131
Epoch 279/300
 - 12s - loss: 3.6116e-04 - acc: 0.8692 - val_loss: 8.3092e-04 - val_acc: 0.8131
Epoch 280/300
 - 12s - loss: 3.5243e-04 - acc: 0.8798 - val_loss: 8.4129e-04 - val_acc: 0.8224
Epoch 281/300
 - 12s - loss: 3.5331e-04 - acc: 0.8698 - val_loss: 8.2661e-04 - val_acc: 0.8131
Epoch 282/300
 - 12s - loss: 3.6111e-04 - acc: 0.8712 - val_loss: 8.1784e-04 - val_acc: 0.8069
Epoch 283/300
 - 12s - loss: 3.5596e-04 - acc: 0.8678 - val_loss: 8.3211e-04 - val_acc: 0.8224
Epoch 284/300
 - 12s - loss: 3.5911e-04 - acc: 0.8632 - val_loss: 8.1398e-04 - val_acc: 0.8115
Epoch 285/300
 - 12s - loss: 3.4721e-04 - acc: 0.8698 - val_loss: 8.4300e-04 - val_acc: 0.8100
Epoch 286/300
 - 12s - loss: 3.5344e-04 - acc: 0.8818 - val_loss: 8.1996e-04 - val_acc: 0.8193
Epoch 287/300
 - 12s - loss: 3.4860e-04 - acc: 0.8858 - val_loss: 8.6560e-04 - val_acc: 0.8162
Epoch 288/300
 - 12s - loss: 3.4780e-04 - acc: 0.8812 - val_loss: 8.3502e-04 - val_acc: 0.8224
Epoch 289/300
 - 12s - loss: 3.4629e-04 - acc: 0.8658 - val_loss: 8.3371e-04 - val_acc: 0.8146
Epoch 290/300
 - 12s - loss: 3.6663e-04 - acc: 0.8792 - val_loss: 8.1299e-04 - val_acc: 0.8131
Epoch 291/300
 - 12s - loss: 3.5419e-04 - acc: 0.8805 - val_loss: 8.1314e-04 - val_acc: 0.8193
Epoch 292/300
 - 12s - loss: 3.5672e-04 - acc: 0.8638 - val_loss: 8.7636e-04 - val_acc: 0.8224
Epoch 293/300
 - 12s - loss: 3.4828e-04 - acc: 0.8758 - val_loss: 8.4624e-04 - val_acc: 0.8115
Epoch 294/300
 - 12s - loss: 3.4688e-04 - acc: 0.8692 - val_loss: 8.2273e-04 - val_acc: 0.8178
Epoch 295/300
 - 12s - loss: 3.4600e-04 - acc: 0.8778 - val_loss: 8.0627e-04 - val_acc: 0.8209
Epoch 296/300
 - 12s - loss: 3.4823e-04 - acc: 0.8852 - val_loss: 8.4006e-04 - val_acc: 0.8037
Epoch 297/300
 - 12s - loss: 3.4888e-04 - acc: 0.8818 - val_loss: 8.1687e-04 - val_acc: 0.8146
Epoch 298/300
 - 12s - loss: 3.4122e-04 - acc: 0.8738 - val_loss: 8.3745e-04 - val_acc: 0.8209
Epoch 299/300
 - 12s - loss: 3.4486e-04 - acc: 0.8852 - val_loss: 8.0453e-04 - val_acc: 0.8209
Epoch 300/300
 - 12s - loss: 3.4072e-04 - acc: 0.8685 - val_loss: 8.1277e-04 - val_acc: 0.8209
In [5]:
model.load_weights('my_model.h5')

Step 7: Visualize the Loss and Test Predictions

(IMPLEMENTATION) Answer a few questions and visualize the loss

Question 1: Outline the steps you took to get to your final neural network architecture and your reasoning at each step.

Answer: started with just 3 convolutional lays with each layer followed by a pooling layer to reduce the dimensionality. Then flatten it to the output. this yielded good results getting a loss of 4.1732e-04 but a val_loss of 0.0012. this shows a sign of over fitting. What i did was just add a dropout layer of 0.5 between the flattening layer and the output layer to reduct the over fitting. These got values of loss: 0.0010 and val_loss: 0.0012 on the last epoch. This is better then the 0.0015 loss. i stuck with this model.

Question 2: Defend your choice of optimizer. Which optimizers did you test, and how did you determine which worked best?

Answer: i tested the Adamax, and Adagrad optimizers as i thought those would probably do very well. my original thoughts were that the Adagrad would do better but i was wrong as it presented signes of over fitting.

Use the code cell below to plot the training and validation loss of your neural network. You may find this resource useful.

In [40]:
## TODO: Visualize the training and validation loss of your neural network
train_loss = hist.history['loss']
val_loss = hist.history['val_loss']

plt.xlabel('number of epochs')
plt.ylabel('loss')
plt.plot(train_loss)
plt.plot(val_loss)
plt.legend(labels=['Training Loss','Validation Loss'])
plt.show()

Question 3: Do you notice any evidence of overfitting or underfitting in the above plot? If so, what steps have you taken to improve your model? Note that slight overfitting or underfitting will not hurt your chances of a successful submission, as long as you have attempted some solutions towards improving your model (such as regularization, dropout, increased/decreased number of layers, etc).

Answer: there were signs of over fitting. what i did was swaped to a different optimizer and i put in a drop in layer with 50% drop out. and that seemed to have solved the issue of over fitting.

Visualize a Subset of the Test Predictions

Execute the code cell below to visualize your model's predicted keypoints on a subset of the testing images.

In [41]:
y_test = model.predict(X_test)
fig = plt.figure(figsize=(20,20))
fig.subplots_adjust(left=0, right=1, bottom=0, top=1, hspace=0.05, wspace=0.05)

for i in range(9):
    ax = fig.add_subplot(3, 3, i + 1, xticks=[], yticks=[])
    plot_data(X_test[i], y_test[i], ax)
    

Step 8: Complete the pipeline

With the work you did in Sections 1 and 2 of this notebook, along with your freshly trained facial keypoint detector, you can now complete the full pipeline. That is given a color image containing a person or persons you can now

  • Detect the faces in this image automatically using OpenCV
  • Predict the facial keypoints in each face detected in the image
  • Paint predicted keypoints on each face detected

In this Subsection you will do just this!

(IMPLEMENTATION) Facial Keypoints Detector

Use the OpenCV face detection functionality you built in previous Sections to expand the functionality of your keypoints detector to color images with arbitrary size. Your function should perform the following steps

  1. Accept a color image.
  2. Convert the image to grayscale.
  3. Detect and crop the face contained in the image.
  4. Locate the facial keypoints in the cropped image.
  5. Overlay the facial keypoints in the original (color, uncropped) image.

Note: step 4 can be the trickiest because remember your convolutional network is only trained to detect facial keypoints in $96 \times 96$ grayscale images where each pixel was normalized to lie in the interval $[0,1]$, and remember that each facial keypoint was normalized during training to the interval $[-1,1]$. This means - practically speaking - to paint detected keypoints onto a test face you need to perform this same pre-processing to your candidate face - that is after detecting it you should resize it to $96 \times 96$ and normalize its values before feeding it into your facial keypoint detector. To be shown correctly on the original image the output keypoints from your detector then need to be shifted and re-normalized from the interval $[-1,1]$ to the width and height of your detected face.

When complete you should be able to produce example images like the one below

In [42]:
def face_recognition(file_path):
    
    # Load in color image for face detection
    image = cv2.imread(file_path)

    # Convert the image to RGB colorspace
    image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

    image_copy= np.copy(image)

    gray = cv2.cvtColor(image_copy,cv2.COLOR_RGB2GRAY)

    face_cascade=cv2.CascadeClassifier('detector_architectures/haarcascade_frontalface_default.xml')

    faces = face_cascade.detectMultiScale(gray,1.4,6)
    print('Number of faces detected: {}'.format(len(faces)))

    fig = plt.figure(figsize=(40, 40))
    ax = fig.add_subplot(121, xticks=[], yticks=[])

    for (x,y,w,h) in faces:
        cv2.rectangle(image_copy,(x,y),(x+w,y+h),(255,255,0),2)
        face_region = gray[y:y+h,x:x+w] #looks at the faces 
        resized = np.reshape(cv2.resize(gray, (96, 96)), (1,96,96,1)) # reshapes it and resizes for fitting the model
        normalized_img = resized/255 #normalizes the image
        keyPoints = model.predict(np.reshape(normalized_img, (1,96,96,1))) #has to reshape it back after normalization. 

        keyPoints = (keyPoints * 49 + 49)* w/96 # gets the points in the right spots.

        #plots points but skips each two in key points as thats X and Y
        ax.scatter((x + keyPoints[0, 0::2]), (y + keyPoints[0, 1::2]), marker='o', c='r', s=30) 

    ax.imshow(image_copy)  
    plt.show()

face_recognition('images/obamas4.jpg')
Number of faces detected: 2

Note: I've tested this out wiht multiple images such as other celeberties like emma watson and the rock. What i noticed was that the model is having trouble with faces that are tilted. I could get around this by havign augmented (rotated and flipped) images in the training data. other then that it is working ok wiht faces that looks straight at the camera.

(Optional) Further Directions - add a filter using facial keypoints to your laptop camera

Now you can add facial keypoint detection to your laptop camera - as illustrated in the gif below.

The next Python cell contains the basic laptop video camera function used in the previous optional video exercises. Combine it with the functionality you developed for keypoint detection and marking in the previous exercise and you should be good to go!

In [46]:
import cv2
import time 
from keras.models import load_model


def laptop_camera_go():
    # Create instance of video capturer
    cv2.namedWindow("face detection activated")
    vc = cv2.VideoCapture(0)

    # Try to get the first frame
    if vc.isOpened(): 
        rval, frame = vc.read()
    else:
        rval = False
    
    # keep video stream open
    
    while rval:
        # plot image from camera with detections marked
        cv2.imshow("face detection activated", frame)
        
        # exit functionality - press any key to exit laptop video
        key = cv2.waitKey(20)
        if key > 0: # exit by pressing any key
            # destroy windows
            cv2.destroyAllWindows()
            
            # hack from stack overflow for making sure window closes on osx --> https://stackoverflow.com/questions/6116564/destroywindow-does-not-close-window-on-mac-using-python-and-opencv
            for i in range (1,5):
                cv2.waitKey(1)
            return
        
        # read next frame
        
        time.sleep(0.05)             # control framerate for computation - default 20 frames per sec
        rval, frame = vc.read()  
        
        gray = cv2.cvtColor(frame, cv2.COLOR_RGB2GRAY)
        
        face_cascade = cv2.CascadeClassifier('detector_architectures/haarcascade_frontalface_default.xml')
        faces = face_cascade.detectMultiScale(gray, 1.1,4)
        
        for (x,y,w,h) in faces:
            cv2.rectangle(frame,(x,y),(x+w,y+h),(255,255,0),2)
            face_region = gray[y:y+h,x:x+w]
            
            #get it ready for model to predict
            resized = np.reshape(cv2.resize(gray, (96, 96)), (1,96,96,1))
            normalized_img = resized/255
            keyPoints = model.predict(np.reshape(normalized_img, (1,96,96,1)))
            
            #putting points into right place
            print(w)
            keyPoints = ((keyPoints * 50+52)* w/103)
            
            plt.imshow(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))
            #need to plot dots onto face
            plt.scatter((x + keyPoints[0, 0::2]), (y + keyPoints[0, 1::2]), marker='o', c='r', s=20) 
         
        
        
laptop_camera_go()
235
239
In [41]:
# Run your keypoint face painter

(Optional) Further Directions - add a filter using facial keypoints

Using your freshly minted facial keypoint detector pipeline you can now do things like add fun filters to a person's face automatically. In this optional exercise you can play around with adding sunglasses automatically to each individual's face in an image as shown in a demonstration image below.

To produce this effect an image of a pair of sunglasses shown in the Python cell below.

In [47]:
# Load in sunglasses image - note the usage of the special option
# cv2.IMREAD_UNCHANGED, this option is used because the sunglasses 
# image has a 4th channel that allows us to control how transparent each pixel in the image is
sunglasses = cv2.imread("images/sunglasses_4.png", cv2.IMREAD_UNCHANGED)

# Plot the image
fig = plt.figure(figsize = (6,6))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])
ax1.imshow(sunglasses)
ax1.axis('off');

This image is placed over each individual's face using the detected eye points to determine the location of the sunglasses, and eyebrow points to determine the size that the sunglasses should be for each person (one could also use the nose point to determine this).

Notice that this image actually has 4 channels, not just 3.

In [48]:
# Print out the shape of the sunglasses image
print ('The sunglasses image has shape: ' + str(np.shape(sunglasses)))
The sunglasses image has shape: (1123, 3064, 4)

It has the usual red, blue, and green channels any color image has, with the 4th channel representing the transparency level of each pixel in the image. Here's how the transparency channel works: the lower the value, the more transparent the pixel will become. The lower bound (completely transparent) is zero here, so any pixels set to 0 will not be seen.

This is how we can place this image of sunglasses on someone's face and still see the area around of their face where the sunglasses lie - because these pixels in the sunglasses image have been made completely transparent.

Lets check out the alpha channel of our sunglasses image in the next Python cell. Note because many of the pixels near the boundary are transparent we'll need to explicitly print out non-zero values if we want to see them.

In [ ]:
# Print out the sunglasses transparency (alpha) channel
alpha_channel = sunglasses[:,:,3]
print ('the alpha channel here looks like')
print (alpha_channel)

# Just to double check that there are indeed non-zero values
# Let's find and print out every value greater than zero
values = np.where(alpha_channel != 0)
print ('\n the non-zero values of the alpha channel look like')
print (values)

This means that when we place this sunglasses image on top of another image, we can use the transparency channel as a filter to tell us which pixels to overlay on a new image (only the non-transparent ones with values greater than zero).

One last thing: it's helpful to understand which keypoint belongs to the eyes, mouth, etc. So, in the image below, we also display the index of each facial keypoint directly on the image so that you can tell which keypoints are for the eyes, eyebrows, etc.

With this information, you're well on your way to completing this filtering task! See if you can place the sunglasses automatically on the individuals in the image loaded in / shown in the next Python cell.

In [ ]:
# Load in color image for face detection
image = cv2.imread('images/obamas4.jpg')

# Convert the image to RGB colorspace
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)


# Plot the image
fig = plt.figure(figsize = (8,8))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])
ax1.set_title('Original Image')
ax1.imshow(image)
In [ ]:
## (Optional) TODO: Use the face detection code we saw in Section 1 with your trained conv-net to put
## sunglasses on the individuals in our test image

(Optional) Further Directions - add a filter using facial keypoints to your laptop camera

Now you can add the sunglasses filter to your laptop camera - as illustrated in the gif below.

The next Python cell contains the basic laptop video camera function used in the previous optional video exercises. Combine it with the functionality you developed for adding sunglasses to someone's face in the previous optional exercise and you should be good to go!

In [ ]:
import cv2
import time 
from keras.models import load_model
import numpy as np

def laptop_camera_go():
    # Create instance of video capturer
    cv2.namedWindow("face detection activated")
    vc = cv2.VideoCapture(0)

    # try to get the first frame
    if vc.isOpened(): 
        rval, frame = vc.read()
    else:
        rval = False
    
    # Keep video stream open
    while rval:
        # Plot image from camera with detections marked
        cv2.imshow("face detection activated", frame)
        
        # Exit functionality - press any key to exit laptop video
        key = cv2.waitKey(20)
        if key > 0: # exit by pressing any key
            # Destroy windows 
            cv2.destroyAllWindows()
            
            for i in range (1,5):
                cv2.waitKey(1)
            return
        
        # Read next frame
        time.sleep(0.05)             # control framerate for computation - default 20 frames per sec
        rval, frame = vc.read()    
        
In [ ]:
# Load facial landmark detector model
model = load_model('my_model.h5')

# Run sunglasses painter
laptop_camera_go()